package com.example.recyclerview;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.recyclerview.databinding.ActivityFruitAddOrUpdateBinding;

public class FruitAddOrUpdateActivity extends AppCompatActivity {
    private ActivityFruitAddOrUpdateBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityFruitAddOrUpdateBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        final Intent intent = getIntent();
        final Bundle extras = intent.getExtras();
        if (extras != null) {
            Fruit fruit = (Fruit) extras.getSerializable("fruit");
            binding.ivFruit.setImageResource(fruit.getImageId());
            binding.etTitle.setText(fruit.getTitle());
            binding.etDescription.setText(fruit.getDescription());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.item_save) {
            String title = binding.etTitle.getText().toString();
            String desc = binding.etDescription.getText().toString();
            if (title.isEmpty() || desc.isEmpty()) {
                Toast.makeText(this, "水果名称和描述不能为空", Toast.LENGTH_SHORT).show();
                return super.onOptionsItemSelected(item);
            }

            Intent intent = new Intent();
            final Bundle bundle = new Bundle();

            final Fruit fruit = new Fruit();
            fruit.setTitle(title);
            fruit.setImageId(R.drawable.apple);
            fruit.setDescription(desc);

            bundle.putSerializable("fruit", fruit);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);

            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}